

const CHUNCK_SIZE = 1024 * 1024 * 5;
const THREAD_COUNT = navigator.hardwareConcurrency || 4;
let finishCount = 0;
export const cutFile = async (file) => {
    return new Promise((resolve) => {
        const result = [];
        const chunckCount = Math.ceil(file.size / CHUNCK_SIZE);
        console.log('chunckCount', chunckCount);
        const workerChunckCount = Math.ceil(chunckCount / THREAD_COUNT);
        for (let i = 0; i < THREAD_COUNT; i++) {
            const worker = new Worker('src/libs/worker.js', {
                type: 'module'
            })
            let startIndex = i * workerChunckCount;
            let  endIndex = startIndex + workerChunckCount;
            if (endIndex > chunckCount) {
                endIndex = chunckCount
            }
          
            worker.postMessage({
                file,
                CHUNCK_SIZE,
                startIndex,
                endIndex
            })
            worker.onmessage = (e) => {
                for (let i = startIndex; i < endIndex; i++) {
                    result[i] = e.data[i - startIndex]
                }
                worker.terminate();
                finishCount++
                if (finishCount === THREAD_COUNT) {
                    resolve(result);
                }
            }
            worker.onerror = function(error) {
                console.error('Worker error:', error.message);
              };
        }


    })


}